/**
 * 工具方法
 * @author 黄淮杰
 */

/**
 * 替换所有指定字符串
 * @param FindText
 * @param RepText
 * @returns {string}
 */
String.prototype.replaceAll = function (FindText, RepText) {
    return this.replace(new RegExp(FindText, "g"), RepText);
};

/**
 * 使用递归的方式实现数组、对象的深拷贝
 * @param obj
 * @returns {[]|{}}
 */
function deepClone(obj) {
    //判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
    let objClone = Array.isArray(obj) ? [] : {};
    //进行深拷贝的不能为空，并且是对象或者是
    if (obj && typeof obj === "object") {
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (obj[key] && typeof obj[key] === "object") {
                    objClone[key] = deepClone(obj[key]);
                } else {
                    objClone[key] = obj[key];
                }
            }
        }
    }
    return objClone;
}

/**
 * 选择器
 * @param el 要选择的元素，类名或者id名
 * @returns {HTMLElement|HTMLCollectionOf<Element>}
 */
function $(el) {
    let start = el.substring(0, 1);
    let end = el.substring(1);
    if (start === "#") {
        return document.getElementById(end);
    } else if (start === ".") {
        return document.getElementsByClassName(end);
    } else {
        throw new Error("选择器参数有误！");
    }
}

/**
 * 下滑显示
 * @param el 要选择的元素，类名或者id
 * @param height 元素的高度
 */
function show(el, height) {
    let a = $(el);
    a.style.visibility = "visible";
    a.style.opacity = "1";
    a.style.height = height + "px";
}

/**
 * 上滑隐藏
 * @param el 要选择的元素，类名或者id
 * @param height 元素的高度
 */
function hide(el, height) {
    let a = $(el);
    a.style.visibility = "hidden";
    a.style.opacity = "0";
    a.style.height = "0";
}

/**
 * 渐入显示
 * @param el 要选择的元素，类名或者id
 * @param second
 */
function fadeIn(el, second) {
    let a = $(el);
    a.style.visibility = "visible";
    a.style.opacity = "1";
    a.style.transition = "all " + second + " linear";
}

/**
 * 渐出隐藏
 * @param el 要选择的元素，类名或者id
 * @param second
 */
function fadeOut(el, second) {
    let a = $(el);
    a.style.visibility = "hidden";
    a.style.opacity = "0";
    a.style.transition = "all " + second + " linear";
}

/**
 * 保存数据到本地
 * @param data
 * @param dataName
 */
function saveDataToLocal(data, dataName) {
    localStorage.setItem(dataName, JSON.stringify(data));
}

/**
 * 从本地取数据
 * @param dataName
 */
function getDataFromLocal(dataName) {
    return localStorage.getItem(dataName) ? JSON.parse(localStorage.getItem(dataName)) : [];
}

/**
 * 日期格式化
 * @param theDate
 * @returns {string}
 */
function formatDateTime(theDate) {

    let _hour = theDate.getHours();
    let _minute = theDate.getMinutes();
    let _second = theDate.getSeconds();
    let _year = theDate.getFullYear();
    let _month = theDate.getMonth();
    let _date = theDate.getDate();

    if (_hour < 10) {
        _hour = "0" + _hour;
    }
    if (_minute < 10) {
        _minute = "0" + _minute;
    }
    if (_second < 10) {
        _second = "0" + _second;
    }
    _month = _month + 1;
    if (_month < 10) {
        _month = "0" + _month;
    }
    if (_date < 10) {
        _date = "0" + _date;
    }
    return _year + "-" + _month + "-" + _date + " " + _hour + ":" + _minute + ":" + _second;
}

/**
 * 获取url参数
 * @param variable
 * @returns {number}
 */
function getQueryVariable(variable) {
    let query = location.search.substring(1);
    let vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        if (pair[0] === variable) {
            return Number(pair[1]);
        }
    }
    return -1;
}

/**
 * 删除数组中的一个元素，返回新数组
 * @param dataList
 * @param id
 * @returns {[]}
 */
function delAnListItem(dataList, id) {
    let newList = [];
    for (let i = 0; i < id - 1; i++) {
        newList.push(dataList[i]);
    }
    for (let i = id; i < dataList.length; i++) {
        dataList[i].id -= 1;
        newList.push(dataList[i]);
    }
    return newList;
}

/**
 * 消息弹窗
 * @param msg
 */
let fadeMessageBox = null;

function message(msg) {
    let messageBox = $("#message-box");
    messageBox.innerText = msg;
    fadeIn("#message-box", ".15s");
    messageBox.style.top = "50%";
    if (fadeMessageBox !== null) {
        clearTimeout(fadeMessageBox);
    }
    fadeMessageBox = setTimeout(function () {
        fadeOut("#message-box", ".15s");
        messageBox.style.top = "55%";
    }, 2000);
}

/**
 * 隐藏遮罩层
 * @type {null}
 */
let fadeConfirmBox = null;

function hideConfirmBox() {
    if (fadeConfirmBox !== null) {
        clearTimeout(fadeConfirmBox);
    }
    fadeConfirmBox = setTimeout(function () {
        fadeOut("#layer-mask", ".15s");
        fadeOut("#confirm-box", ".15s");
        $("#confirm-box").style.top = "55%";
    }, 100);
}

/**
 * 确认弹窗
 * @param msg
 * @param callback
 */
function myConfirm(msg, callback) {
    let confirmBox = $("#confirm-box");
    let btnConfirm = $("#btn-confirm");
    let btnCancel = $("#btn-cancel");
    let closeConfirm = $("#close-confirm");
    $("#confirm-content").innerText = msg;
    fadeIn("#layer-mask", ".15s");
    fadeIn("#confirm-box", ".15s");
    confirmBox.style.top = "50%";
    btnConfirm.onclick = function () {
        hideConfirmBox();
        callback();
    };
    btnCancel.onclick = function () {
        message("您已经取消操作！");
        hideConfirmBox();
    };
    closeConfirm.onclick = function () {
        message("您已经取消操作！");
        hideConfirmBox();
    };
}

/**
 * 警告（元素背景变红）
 * @param {*} el
 * @param {*} time
 */
function warn(el, time) {
    el.style.backgroundColor = "rgba(255,70,70,0.29)";
    setTimeout(function () {
        el.style.backgroundColor = "#ffffff";
    }, time);
}

/**
 * 成功（元素背景变率）
 * @param {*} el
 * @param {*} time
 */
function success(el, time) {
    el.style.backgroundColor = "rgba(136,190,255,0.29)";
    setTimeout(function () {
        el.style.backgroundColor = "#fff";
    }, time);
}

/**
 * 把字符串动态创建出dom对象
 * @param arg 插入的dom字符串内容
 */
function parseDom(arg) {
    var objE = document.createElement("div");
    objE.innerHTML = arg;
    return objE.childNodes;
}

/**
 * 从下往上渐入
 * @param el
 * @param second
 */
function fadeInFromDown(el, second) {
    el.style.visibility = "hidden";
    el.style.opacity = 0;
    el.style.transation = "";
    el.style.transform = "translateY(" + el.offsetHeight + "px)";
    el.style.boxShadow = "0 0 25px rgba(0, 0, 0, 1)";
    setTimeout(function () {
        el.style.visibility = "visible";
        el.style.opacity = "1";
        el.style.transform = "translateY(0)";
        el.style.boxShadow = ""
    }, second);
}

/**
 * 从上往下渐入
 * @param el
 * @param second
 */
function fadeInFromTop(el, second) {
    el.style.visibility = "hidden";
    el.style.opacity = 0;
    el.style.transation = "";
    el.style.transform = "translateY(-" + el.offsetHeight + "px)";
    el.style.boxShadow = "0 0 25px rgba(0, 0, 0, 1)";
    setTimeout(function () {
        el.style.visibility = "visible";
        el.style.opacity = "1";
        el.style.transform = "translateY(0)";
        el.style.boxShadow = "";
    }, second);
}

function slideToUp(el) {
    el.style.transform = "translateY(-" + el.offsetHeight + "px)"
}

function slideToDown(el) {
    el.style.transform = "translateY(0)"
}

/**
 * 获取滚动条距离顶端的距离
 * @return {}支持IE6
 */
function getScrollTop() {
    let scrollPos;
    if (window.pageYOffset) {
        scrollPos = window.pageYOffset;
    } else if (document.compatMode && document.compatMode !== 'BackCompat') {
        scrollPos = document.documentElement.scrollTop;
    } else if (document.body) {
        scrollPos = document.body.scrollTop;
    }
    return scrollPos;
}

/**
 * 隐藏和显示导航栏
 */
function headerAnimation() {
    window.addEventListener("scroll", function (e) {
        if (getScrollTop() >= 100) {
            slideToUp($("#header"));
        } else {
            slideToDown($("#header"));
        }
    })
}

/**
 *
 * @param {要展示的索引页数} totalIndexCount
 * @param {当前索引页} currentPage
 * @param {总页数} totalPage
 */
//返回展示开始的索引和结束的索引
function pageIndex(totalIndexCount, currentPage, totalPage) {
    //开始索引
    let beginIndex = 0;
    //结束索引
    let endIndex = 0;

    let startPageIndex = currentPage - (totalIndexCount % 2 == 0 ? parseInt(totalIndexCount / 2) - 1 : parseInt(totalIndexCount / 2));
    let endPageIndex = currentPage + parseInt(totalIndexCount / 2);
    if (startPageIndex < 1) {
        startPageIndex = 1;
        if (totalPage >= totalIndexCount) {
            endPageIndex = totalIndexCount;
        } else {
            endPageIndex = totalPage;
        }
    }
    if (endPageIndex > totalPage) {
        endPageIndex = totalPage;
        if ((endPageIndex - totalIndexCount) > 0) {
            startPageIndex = endPageIndex - totalIndexCount + 1;
        } else {
            startPageIndex = 1;
        }
    }
    //返回开始索引和结束索引
    return {
        beginIndex: startPageIndex,
        endIndex: endPageIndex
    }

}
//格式化年月日格式为yyyymmdd
function timeFormat(str) {
    if (Number(str) < 10) {
        return '0' + str;
    } else {
        return str;
    }
}
